import {
  CheckCircleOutlined,
  PlusOutlined,
  SearchOutlined,
  UploadOutlined,
} from '@ant-design/icons';
import { Button, message, Drawer, FormInstance, Popconfirm, Image, Modal, Upload, Tag } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  ModalForm,
  ProFormText,
  ProFormRadio,
  ProFormSelect,
  ProFormDependency,
  ProFormDigit,
  DrawerForm,
  ProForm,
  ProFormDatePicker,
} from '@ant-design/pro-form';
import ProDescriptions, { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import {
  removeData,
  dataList,
  addData,
  updateData,
  loadData,
  loadSelectTag,
  questionList,
  coursewareList,
  coursewareListSave,
  updateCourse,
  employeeListSave,
  employeeList,
  publishData,
  unPublishData,
} from './service';
import type { PlanBody, PlanListItem, PlanListPagination } from './data';

import { CoursewareItem, QuestionItem } from './data';
import CoursewareList from '@/pages/Train/Courseware/list';
import { CoursewareListItem } from '@/pages/Train/Courseware/data';
import { download } from '@/pages/Train/Courseware/service';
import EmployeeSelect from '@/pages/Employee/List/select';
import { EmployeeListItem } from '@/pages/Employee/List/data';
import moment, { Moment } from 'moment';
import 'moment/locale/zh-cn';

/**
 * 添加节点
 *
 * @param fields
 * @param mode
 */

const handleAdd = async (fields: PlanBody, mode: boolean) => {
  const hide = message.loading(mode ? '正在保存' : '正在添加');

  try {
    mode ? await updateData({ ...fields }) : await addData({ ...fields });
    hide();
    message.success(mode ? '保存成功' : '添加成功');
    return true;
  } catch (error) {
    // hide();
    // message.error(mode ? '保存失败请重试' : '添加失败请重试');
    return false;
  }
};
const handleSaveCourse = async (fields: PlanBody) => {
  const hide = message.loading('正在保存');

  try {
    await updateCourse({ ...fields });
    hide();
    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: PlanListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeData(selectedRows.map((row) => row.planId));
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const handlePublish = async (selectedRows: PlanListItem) => {
  const hide = message.loading('正在发布');
  if (!selectedRows) return true;
  try {
    await publishData(selectedRows.planId);
    hide();
    message.success('发布成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('发布失败，请重试');
    return false;
  }
};
const handleUnPublish = async (selectedRows: PlanListItem) => {
  const hide = message.loading('正在取消发布');
  if (!selectedRows) return true;
  try {
    await unPublishData(selectedRows.planId);
    hide();
    message.success('取消发布成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('取消发布失败，请重试');
    return false;
  }
};
const requestTag = async () => {
  return loadSelectTag().then(({ data }) => {
    return data;
  });
};
const PlanPostPage: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [coursewareModalVisible, handleCoursewareModalVisible] = useState<boolean>(false);
  const [employeeModalVisible, handleEmployeeModalVisible] = useState<boolean>(false);
  const [selectCoursewareModalVisible, handleSelectCoursewareModalVisible] =
    useState<boolean>(false);
  const [selectEmployeeModalVisible, handleSelectEmployeeModalVisible] = useState<boolean>(false);
  const [coursewareType, setCoursewareType] = useState<number>(1);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const actionQuestionRef = useRef<ActionType>();
  const actionCoursewareRef = useRef<ActionType>();
  const actionEmployeeRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const formCoursewareRef = useRef<FormInstance>();
  const [currentRow, setCurrentRow] = useState<PlanListItem>();
  const columns: ProColumns<PlanListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionRef?.current?.pageInfo?.current || 1) - 1) *
                (actionRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '计划名称',
      dataIndex: 'name',
    },
    {
      title: '是否考试',
      dataIndex: 'exam',
      valueEnum: {
        0: {
          text: '不考试',
          status: 'Default',
        },
        1: {
          text: '考试',
          status: 'Success',
        },
      },
    },
    {
      title: '状态',
      dataIndex: 'publish',
      valueEnum: {
        0: {
          text: '未发布',
          status: 'Error',
        },
        1: {
          text: '已发布',
          status: 'Success',
        },
      },
    },
    {
      title: '标签',
      dataIndex: 'tags',
      request: requestTag,
      render: (_, record) => (
        <>
          {record?.tagNames?.map((name, index) => (
            <Tag key={name + index + record.planId}>{name}</Tag>
          ))}
        </>
      ),
    },
    {
      search: false,
      title: '开始时间',
      dataIndex: 'startTime',
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '更新时间',
      sorter: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInDescriptions: true,
      render: (_, record) => {
        if (record.publish == 0) {
          return [
            <a
              key="view"
              onClick={() => {
                formRef.current?.resetFields();
                setCurrentRow(record);
                setShowDetail(true);
              }}
            >
              查看
            </a>,
            <a
              key="edit"
              onClick={() => {
                formRef.current?.resetFields();
                console.log(record);
                setCurrentRow(record);
                setEditMode(true);
                handleModalVisible(true);
              }}
            >
              编辑
            </a>,
            <Popconfirm
              key="delete"
              okButtonProps={{ danger: true }}
              title={`确认删除计划：${record.name}?`}
              onConfirm={async () => {
                setCurrentRow(record);
                await handleRemove([record]);
                actionRef.current?.reloadAndRest?.();
              }}
              okText="删除"
              cancelText="取消"
            >
              <a href="@/pages/Defense/System/Assessment/post#"> 删除 </a>
            </Popconfirm>,
            <a
              key="employee"
              onClick={() => {
                setCurrentRow(record);
                handleEmployeeModalVisible(true);
              }}
            >
              学员设置
            </a>,

            <a
              key="courseware"
              onClick={() => {
                setCurrentRow(record);
                handleCoursewareModalVisible(true);
              }}
            >
              课件设置
            </a>,
            <Popconfirm
              key="publish1"
              okButtonProps={{ danger: true }}
              title={`确认发布计划：${record.name}?`}
              onConfirm={async () => {
                setCurrentRow(record);
                await handlePublish(record);
                actionRef.current?.reloadAndRest?.();
              }}
              okText="发布"
              cancelText="取消"
            >
              <a href="@/pages/Defense/System/Assessment/post#"> 发布 </a>
            </Popconfirm>,
          ];
        } else
          return [
            <a
              key="view"
              onClick={() => {
                formRef.current?.resetFields();
                setCurrentRow(record);
                setShowDetail(true);
              }}
            >
              查看
            </a>,

            <a
              key="employee"
              onClick={() => {
                setCurrentRow(record);
                handleEmployeeModalVisible(true);
              }}
            >
              学员设置
            </a>,

            <Popconfirm
              key="publish"
              okButtonProps={{ danger: true }}
              title={`确认取消发布计划：${record.name}?`}
              onConfirm={async () => {
                setCurrentRow(record);
                await handleUnPublish(record);
                actionRef.current?.reloadAndRest?.();
              }}
              okText="取消发布"
              cancelText="取消"
            >
              <a href="@/pages/Defense/System/Assessment/post#"> 取消发布 </a>
            </Popconfirm>,
          ];
      },
    },
  ];

  const questionColumns: ProColumns<QuestionItem>[] = [
    {
      title: '序号',
      width: 50,
      align: 'center',
      dataIndex: 'index',
      valueType: 'indexBorder',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionQuestionRef?.current?.pageInfo?.current || 1) - 1) *
                (actionQuestionRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '题目',
      dataIndex: 'title',
    },
    {
      title: '选项',
      dataIndex: 'options',
      render: (_, record) => (
        <>
          {record?.options?.map((name, index) => (
            <div>
              <Tag
                icon={name.answer ? <CheckCircleOutlined /> : <></>}
                color={name.answer ? 'success' : ''}
                key={name.key + index + record.questionId}
              >
                {name.key}.{name.text}
              </Tag>
              <br />
            </div>
          ))}
        </>
      ),
    },
  ];
  // const [selectCourseware, setSelectCourseware] = useState<CoursewareListItem[]>([]);
  const [selectCoursewareKey, setSelectCoursewareKey] = useState<React.Key[]>([]);
  // const [selectEmployee, setSelectEmployee] = useState<CoursewareListItem[]>([]);
  const [selectEmployeeKey, setSelectEmployeeKey] = useState<React.Key[]>([]);

  const coursewareColumns: ProColumns<CoursewareItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 50,
      align: 'center',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionCoursewareRef?.current?.pageInfo?.current || 1) - 1) *
                (actionCoursewareRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '课件名称',
      dataIndex: 'name',
    },
    {
      search: false,
      title: '时长',
      width: 100,
      dataIndex: 'time',
      render: (_, record) => (
        <>
          {Math.floor((record.time ?? 0) / 60)}分{(record.time ?? 0) % 60}秒
        </>
      ),
    },
    {
      search: false,
      title: '题数',
      width: 50,
      dataIndex: 'questionNum',
    },
  ];

  const employeeColumns: ProColumns<EmployeeListItem>[] = [
    {
      dataIndex: 'index',
      width: 48,
      align: 'center',
      valueType: 'index',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionEmployeeRef?.current?.pageInfo?.current || 1) - 1) *
                (actionEmployeeRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '员工姓名',
      key: 'name',
      dataIndex: 'name',
    },
    {
      title: '手机号',
      key: 'mobile',
      dataIndex: 'mobile',
    },
    {
      title: '身份证号',
      key: 'idCard',
      dataIndex: 'idCard',
    },
  ];

  const [editMode, setEditMode] = useState<boolean>(false);
  const [previewData, setPreviewData] = useState({
    visible: false,
    image: '',
    title: '',
  });

  const uploadProps = {
    headers: {
      Authorization: `Bearer ${localStorage.getItem('token')}`,
    },
    multiple: false,
    // onPreview: async (file: UploadFile) => {
    //   window.open(file?.response?.data?.path || file.url, '_blank')
    // },
    name: 'file',
    max: 1,
  };
  const handleCloseSelectCoursewareModal = () => {
    handleSelectCoursewareModalVisible(false);
  };

  const handleSaveSelectCoursewareModal = async () => {
    const hide = message.loading('正在保存课件');
    if (!currentRow) return true;
    try {
      await coursewareListSave(currentRow?.planId, selectCoursewareKey);
      hide();
      message.success('课件保存成功，即将刷新');
      handleSelectCoursewareModalVisible(false);
      // @ts-ignore
      actionCoursewareRef.current?.reloadAndRest();
      return true;
    } catch (error) {
      hide();
      message.error('课件保存失败，请重试');
      return false;
    }
  };
  const handleCloseSelectEmployeeModal = () => {
    handleSelectEmployeeModalVisible(false);
  };
  const handleSaveSelectEmployeeModal = async () => {
    const hide = message.loading('正在保存');
    if (!currentRow) return true;
    try {
      await employeeListSave(currentRow?.planId, selectEmployeeKey);
      hide();
      message.success('保存成功，即将刷新');
      handleSelectEmployeeModalVisible(false);
      // @ts-ignore
      actionEmployeeRef?.current?.reloadAndRest();
      return true;
    } catch (error) {
      hide();
      message.error('保存失败，请重试');
      return false;
    }
  };
  const disabledDate = (current: Moment) => {
    return current && current < moment().subtract(1, 'days').endOf('day');
  };
  return (
    <PageContainer waterMarkProps={{ content: '' }}>
      <ProTable<PlanListItem, PlanListPagination>
        headerTitle="计划列表"
        actionRef={actionRef}
        rowKey="planId"
        search={{
          labelWidth: 120,
        }}
        options={false}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setEditMode(false);
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={dataList}
        columns={columns}
        // @ts-ignore
        params={{ category: 1 }}
      />
      <ModalForm<PlanBody>
        title={currentRow?.planId || 0 > 0 ? '编辑计划' : '新建计划'}
        formRef={formRef}
        layout={'horizontal'}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        visible={createModalVisible}
        // onValuesChange={(changedValues, values) => {
        //   if (changedValues && changedValues.hasOwnProperty("dateRange")) {
        //     formRef.current?.setFieldsValue({startTime: changedValues.dateRange[0] + " 00:00:00"});
        //     formRef.current?.setFieldsValue({endTime: changedValues.dateRange[1] + " 00:00:00"});
        //   }
        // }}
        onVisibleChange={(visible) => {
          if (!visible) {
            setCurrentRow(undefined);
          }
          handleModalVisible(visible);
        }}
        modalProps={{destroyOnClose: true, maskClosable: false}}
        onFinish={async (value) => {
          console.log(value);
          // @ts-ignore
          if (value?.startTime?.indexOf('00:00:00') < 0) {
            value.startTime = value.startTime + ' 00:00:00';
          }
          console.log(value);
          const success = await handleAdd(value, editMode);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              // @ts-ignore
              actionRef?.current?.reloadAndRest();
            }
          }
        }}
        // @ts-ignore
        request={(params: PlanBody) => {
          console.log(params);
          if (params.planId > 0) {
            return loadData(params).then(({ data }) => {
              data.dateRange = [data.startTime ?? '', data.endTime ?? ''];
              data.startTime = data.startTime + ' 00:00:00';
              // data.endTime = data.endTime + " 00:00:00"
              if (data.tags) data.tagList = data.tags;
              return data;
            });
          } else {
            return new Promise<PlanBody>((resolve) => {
              resolve({
                planId: 0,
                coursewareType: 1,
                exam: 0,
                examPassScore: 80,
              });
            });
          }
        }}
        params={{ ...currentRow }}
      >
        <ProFormText hidden name="planId" />
        <ProFormText hidden name="startTime" />
        <ProFormText hidden name="endTime" />
        <ProFormText hidden name="sort" initialValue={0} />
        <ProFormText hidden name="category" initialValue={1} />
        <ProFormText rules={[{ required: true }]} label={'计划名称'} name="name" />
        <ProFormRadio.Group
          name="coursewareType"
          rules={[{ required: true, message: '请选择课件类型' }]}
          label="课件类型"
          extra={'视频可以选择多个课件，PDF文档只能选择一个'}
          options={[
            {
              label: '视频',
              value: 1,
            },
            {
              label: 'PDF文档',
              value: 2,
            },
          ]}
        />
        <ProFormRadio.Group
          name="exam"
          rules={[{ required: true, message: '请设置是否需要考试' }]}
          label="是否需要考试"
          options={[
            {
              label: '不考试',
              value: 0,
            },
            {
              label: '考试',
              value: 1,
            },
          ]}
        />
        <ProFormDependency name={['exam']}>
          {({ exam }) => {
            if (exam == 1) {
              return (
                <ProFormDigit
                  label="及格分数"
                  rules={[{ required: true }]}
                  name="examPassScore"
                  min={0}
                  max={100}
                  fieldProps={{ precision: 0 }}
                />
              );
            }
            return <></>;
          }}
        </ProFormDependency>

        <ProFormDatePicker
          rules={[{ required: true }]}
          name="startTime"
          label="开始时间"
          fieldProps={{ disabledDate }}
        />

        <ProFormSelect
          name="tagList"
          label="计划标签"
          mode={'tags'}
          request={requestTag}
          // valueEnum={{
          //   open: '未解决',
          //   closed: '已解决',
          // }}
          extra={'没有合适的标签可以直接输入'}
          placeholder="请选择计划标签，没有合适的标签可以直接输入"
          rules={[{ required: true, message: '请设置计划标签!' }]}
        />
      </ModalForm>
      <DrawerForm<PlanBody>
        title={'课程设置'}
        formRef={formCoursewareRef}
        layout={'horizontal'}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        visible={coursewareModalVisible}
        onValuesChange={(changedValues, values) => {
          console.log(changedValues);
          if (changedValues && changedValues.hasOwnProperty('coursewareType')) {
            setCoursewareType(values.coursewareType);
          }
        }}
        onVisibleChange={(visible) => {
          if (!visible) {
            setCurrentRow(undefined);
          }
          handleCoursewareModalVisible(visible);
        }}
        drawerProps={{
          destroyOnClose: true,
          maskClosable: false,
        }}
        submitter={{
          searchConfig: {
            submitText: '保存',
            resetText: '取消',
          },
        }}
        onFinish={async (value) => {
          console.log(value);
          const success = await handleSaveCourse(value);
          if (success) {
            handleCoursewareModalVisible(false);
            // @ts-ignore
            actionRef?.current?.reloadAndRest();
          }
        }}
        // @ts-ignore
        request={(params: PlanBody) => {
          console.log(params);
          if (params.planId) {
            return loadData(params).then(({ data }) => {
              data.dateRange = [data.startTime ?? '', data.endTime ?? ''];
              data.startTime = data.startTime + ' 00:00:00';
              data.endTime = data.endTime + ' 00:00:00';
              if (data.tags) data.tagList = data.tags;
              setCoursewareType(data.coursewareType ?? 0);

              return data;
            });
          }
        }}
        params={{ ...currentRow }}
      >
        <ProFormText hidden name="planId" />
        <ProFormText readonly label={'计划名称'} name="name" />
        <ProFormRadio.Group
          name="coursewareType"
          label="课件类型"
          extra={'视频可以选择多个课件，PDF文档只能选择一个'}
          disabled
          options={[
            {
              label: '视频',
              value: 1,
            },
            {
              label: 'PDF文档',
              value: 2,
            },
          ]}
        />
        <ProForm.Item label={'培训课件'}>
          <ProTable<CoursewareListItem>
            size={'small'}
            cardProps={{
              bodyStyle: { padding: 0 },
            }}
            scroll={{ y: 200 }}
            // dataSource={selectCourseware}
            request={async () => {
              let newVar = await coursewareList(currentRow?.planId ?? 0);
              console.log(newVar);
              // @ts-ignore
              setSelectCoursewareKey(newVar.data.map((row) => row.coursewareId));

              return {
                data: newVar.data,
                // success 请返回 true，
                // 不然 table 会停止解析数据，即使有数据
                success: true,
                // 不传会使用 data 的长度，如果是分页一定要传
                total: newVar.data.length,
              };
            }}
            rowKey="coursewareId"
            bordered
            options={false}
            pagination={false}
            actionRef={actionCoursewareRef}
            columns={coursewareColumns}
            search={false}
            dateFormatter="string"
          />
          <div style={{ textAlign: 'right' }}>
            <Button
              type="primary"
              key="primary"
              style={{ marginTop: 15 }}
              icon={<SearchOutlined />}
              onClick={() => {
                handleSelectCoursewareModalVisible(true);
              }}
            >
              选择课件
            </Button>
          </div>
        </ProForm.Item>
        <ProFormRadio.Group
          name="exam"
          rules={[{ required: true, message: '请设置是否考试' }]}
          label="是否考试"
          options={[
            {
              label: '不考试',
              value: 0,
            },
            {
              label: '考试',
              value: 1,
            },
          ]}
        />
        <ProFormDependency name={['exam']}>
          {({ exam }) => {
            if (exam == 1) {
              return (
                <>
                  <ProFormDigit
                    label="及格分数"
                    rules={[{ required: true }]}
                    name="examPassScore"
                    min={0}
                    max={100}
                    fieldProps={{ precision: 0 }}
                  />
                  <ProFormRadio.Group
                    name="questionType"
                    rules={[{ required: true, message: '请设置出题方式' }]}
                    label="出题方式"
                    options={[
                      {
                        label: '所选课件的全部题目',
                        value: 0,
                      },
                      {
                        label: '在所选课件中随机抽取',
                        value: 1,
                      },
                      {
                        label: '自定义',
                        value: 2,
                      },
                    ]}
                  />

                  <ProFormDependency name={['questionType']}>
                    {({ questionType }) => {
                      if (questionType == 1) {
                        return (
                          <ProFormDigit
                            label="抽取题数"
                            rules={[{ required: true }]}
                            name="questionNum"
                            min={1}
                            extra={'最少抽取一道题'}
                            fieldProps={{ precision: 0 }}
                          />
                        );
                      } else if (questionType == 2) {
                        return (
                          <ProForm.Item label={'上传试题'}>
                            <ProTable<QuestionItem>
                              request={async () => {
                                let newVar = await questionList(currentRow?.planId ?? 0);
                                console.log(newVar);
                                return {
                                  data: newVar.data,
                                  // success 请返回 true，
                                  // 不然 table 会停止解析数据，即使有数据
                                  success: true,
                                  // 不传会使用 data 的长度，如果是分页一定要传
                                  total: newVar.data.length,
                                };
                              }}
                              rowKey={'questionId'}
                              size={'small'}
                              cardProps={{
                                bodyStyle: { padding: 0 },
                              }}
                              scroll={{ y: 200 }}
                              bordered
                              pagination={false}
                              columns={questionColumns}
                              options={false}
                              search={false}
                              actionRef={actionQuestionRef}
                              dateFormatter="string"
                            />
                            <div style={{ textAlign: 'right', marginTop: 5 }}>
                              <div style={{ color: 'red', textAlign: 'right', marginBottom: 5 }}>
                                注意:上传题目将会覆盖原有题目
                              </div>
                              <div>
                                <Button onClick={download} key={'download'}>
                                  下载模板
                                </Button>
                                &nbsp;&nbsp;&nbsp;
                                <Upload
                                  key="upload"
                                  style={{ width: '100%' }}
                                  {...uploadProps}
                                  accept={'.xls,.xlsx'}
                                  action={
                                    '/v2/enterprise/train/plan/question/upload/' +
                                    currentRow?.planId
                                  }
                                  showUploadList={false}
                                  onChange={async (data) => {
                                    let file = data.file;
                                    if (file.status === 'done' && file.response.code !== 200) {
                                      file.status = 'error';
                                    } else if (
                                      file.status === 'done' &&
                                      file.response.code === 200
                                    ) {
                                      // @ts-ignore
                                      actionQuestionRef.current?.reloadAndRest();
                                    }
                                  }}
                                >
                                  <Button type="primary" block icon={<UploadOutlined />}>
                                    上传题目
                                  </Button>
                                </Upload>
                              </div>
                            </div>
                          </ProForm.Item>
                        );
                      }
                      return <></>;
                    }}
                  </ProFormDependency>
                </>
              );
            }
            return <></>;
          }}
        </ProFormDependency>
      </DrawerForm>
      <DrawerForm<PlanBody>
        title={'学员管理'}
        formRef={formCoursewareRef}
        layout={'horizontal'}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        visible={employeeModalVisible}
        onVisibleChange={(visible) => {
          if (!visible) {
            setCurrentRow(undefined);
          }
          handleEmployeeModalVisible(visible);
        }}
        drawerProps={{
          destroyOnClose: true,
          maskClosable: false,
        }}
        submitter={{
          searchConfig: {
            submitText: '保存',
            resetText: '关闭',
          },
          submitButtonProps: {
            style: {
              display: 'none',
            },
          },
        }}
        onFinish={async (value) => {
          handleEmployeeModalVisible(false);
        }}
        // @ts-ignore
        request={(params: PlanBody) => {
          console.log(params);
          if (params.planId) {
            return loadData(params).then(({ data }) => {
              data.dateRange = [data.startTime ?? '', data.endTime ?? ''];
              data.startTime = data.startTime + ' 00:00:00';
              data.endTime = data.endTime + ' 00:00:00';
              if (data.tags) data.tagList = data.tags;
              setCoursewareType(data.coursewareType ?? 0);

              return data;
            });
          }
        }}
        params={{ ...currentRow }}
      >
        <ProFormText hidden name="planId" />
        <ProFormText readonly label={'计划名称'} name="name" />
        <ProForm.Item label={'学员列表'}>
          <ProTable<EmployeeListItem>
            size={'small'}
            cardProps={{
              bodyStyle: { padding: 0 },
            }}
            scroll={{ y: 500 }}
            // dataSource={selectCourseware}
            request={async () => {
              let newVar = await employeeList(currentRow?.planId ?? 0);
              console.log(newVar);
              // @ts-ignore
              setSelectEmployeeKey(newVar.data.map((row) => row.employeeId));

              return {
                data: newVar.data,
                // success 请返回 true，
                // 不然 table 会停止解析数据，即使有数据
                success: true,
                // 不传会使用 data 的长度，如果是分页一定要传
                total: newVar.data.length,
              };
            }}
            rowKey="employeeId"
            bordered
            options={false}
            pagination={false}
            actionRef={actionEmployeeRef}
            columns={employeeColumns}
            search={false}
            dateFormatter="string"
          />
          <div style={{ textAlign: 'right' }}>
            <Button
              type="primary"
              key="primary"
              style={{ marginTop: 15 }}
              icon={<SearchOutlined />}
              onClick={() => {
                handleSelectEmployeeModalVisible(true);
              }}
            >
              选择学员
            </Button>
          </div>
        </ProForm.Item>
      </DrawerForm>

      <Modal
        title={'课件选择'}
        visible={selectCoursewareModalVisible}
        onOk={handleSaveSelectCoursewareModal}
        onCancel={handleCloseSelectCoursewareModal}
        destroyOnClose={true}
        bodyStyle={{ padding: 20, background: '#f0f2f5' }}
        width={1000}
        maskClosable={false}
      >
        <CoursewareList
          selectMode={true}
          type={coursewareType}
          keys={selectCoursewareKey}
          onSelectData={(_, __) => {
            console.log(_, __);
            setSelectCoursewareKey(_);
          }}
        />
      </Modal>
      <Modal
        title={'学员选择'}
        visible={selectEmployeeModalVisible}
        onOk={handleSaveSelectEmployeeModal}
        onCancel={handleCloseSelectEmployeeModal}
        destroyOnClose={true}
        bodyStyle={{ padding: 20, background: '#f0f2f5' }}
        width={1000}
        maskClosable={false}
      >
        <EmployeeSelect
          keys={selectEmployeeKey}
          onSelectData={(_, __) => {
            console.log(_, __);
            setSelectEmployeeKey(_);
          }}
        />
      </Modal>
      <Image
        width={200}
        style={{ display: 'none' }}
        src={previewData.image}
        preview={{
          visible: previewData.visible,
          src: previewData.image,
          onVisibleChange: (value) => {
            setPreviewData({ image: previewData.image, title: '', visible: value });
          },
        }}
      />
      <Drawer
        width={800}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.planId && (
          <ProDescriptions<PlanBody>
            column={1}
            bordered={true}
            title={'计划详情'}
            // @ts-ignore
            request={loadData}
            // layout={'vertical'}
            params={currentRow}
            columns={columns as ProDescriptionsItemProps<PlanBody>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default PlanPostPage;
